package com.yyq.aclservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyq.aclservice.entity.User;
import com.yyq.aclservice.service.IndexService;
import com.yyq.aclservice.service.UserService;
import com.yyq.result.JwtUtils;
import com.yyq.result.MD5;
import com.yyq.result.R;
import com.yyq.servicebase.exceptionhandler.YyqException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/acl/index")
@CrossOrigin
public class IndexController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private UserService userService;

    @GetMapping("login/{username}/{password}")
    public R login(@PathVariable String username,@PathVariable String password){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);

        User user = userService.getOne(wrapper);
        if(user==null) throw new YyqException(20001,"找不到用户");
        if(!MD5.encrypt(password).equals(user.getPassword())) throw new YyqException(20001,"密码错误");

        //登录成功
        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getNickName());
        return R.ok().data("token",jwtToken);


    }

    /**
     * 根据token获取用户信息
     */
    @GetMapping("info")
    public R info(HttpServletRequest request){
        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println("%%%%%%%%%%%%%%%"+memberid);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",memberid);
        User byId = userService.getOne(wrapper);
      //return    R.ok().data("roles","admin").data("name","admin").data("avatar","https://www.jianfast.com/static/home/images/siteimg/i4.png");
        //获取当前登录用户用户名
        String username =byId.getUsername();
        Map<String, Object> userInfo = indexService.getUserInfo(username);
        return R.ok().data(userInfo);
    }

    /**
     * 获取菜单
     * @return
     */
    @GetMapping("menu")
    public R getMenu(HttpServletRequest request){

        String memberid = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println("%%%%%%%%%%%%%%%"+memberid);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",memberid);
        User byId = userService.getOne(wrapper);
        //获取当前登录用户用户名
       // String username = SecurityContextHolder.getContext().getAuthentication().getName();
        String username=byId.getUsername();
        List<JSONObject> permissionList = indexService.getMenu(username);
        return R.ok().data("permissionList", permissionList);
    }

    @PostMapping("logout")
    public R logout(){
        return R.ok();
    }

}
